//
//  MapViewController.m
//  MapTextDemo
//
//  Created by zcj on 2018/4/16.
//  Copyright © 2018年 zcj. All rights reserved.
//

#import "MapViewController.h"
#import <Foundation/Foundation.h>
#import "SearchCell.h"
/**  高德地图  **/
#import <MAMapKit/MAMapKit.h>
#import <MAMapKit/MAMapView.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
@interface   MapViewController()<MAMapViewDelegate,AMapSearchDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (nonatomic, strong) MAMapView            *mapView; //地图
@property (nonatomic, strong) AMapSearchAPI        *search;  //搜索sdk
@property (nonatomic, strong) UIView               *searchView; //搜索View
@property (nonatomic, strong) UITextField           *searchText;  //输入搜索提示语
@property (nonatomic, strong) UITableView          *searchTableView; //展示搜索出来的结果
@property (nonatomic, strong) UIView               *mengbanView; //半透明蒙板，上面有tableView
@property (nonatomic, strong) UIView               *bottomView;
@property (nonatomic, strong) UIButton             *sureBtn;
@property (nonatomic, strong) UIImageView          *centerAnnotationView;
@property (nonatomic, strong) UIView                *annotationView;
@property (nonatomic, strong) UILabel               *AnnotationTitleLabel;
@property (nonatomic, strong) UILabel               *AnnotationContentLabel;

@property (nonatomic, strong) UILabel               *addressTitleLabel;
@property (nonatomic, strong) UILabel               *addressContentLabel;
@property (nonatomic, assign) NSInteger             searchPage;

@property (nonatomic, copy) NSString              *cityName;
@property (nonatomic, copy) NSString               *currentType;
@property (nonatomic, copy) NSString              *addressTiele;//地址的标题
@property (nonatomic, copy) NSString               *addressContent;//地址的内容
//@property (nonatomic, copy) NSString              *name;//联系人名字
//@property (nonatomic, copy) NSString               *phone;//联系人电话
@property (nonatomic, assign) CLLocationCoordinate2D locationCoordinate;

@property (nonatomic, copy) NSArray                *searchTypes;
@property (nonatomic, strong) NSMutableArray       *searchPoiArray;//进来之后根据中心点坐标搜索出来的数组
@property (nonatomic, strong) NSMutableArray        *tipsArray;//输入提示语搜索出来的数组
@property (nonatomic, strong) NSMutableArray        *tempArray;//输入提示语搜索出来的数组

//@property (nonatomic,copy) NSString *strCountryCode; // 编码


//@property (nonatomic, strong) UIView               *addressView;
@property (nonatomic, strong) FlexFrameView               *addressView;

///省/直辖市
@property (nonatomic, copy)   NSString         *strProvince;
@property (nonatomic, copy)   NSString         *strProvinceCode;

///市
@property (nonatomic, copy)   NSString         *strCity;
///城市编码
@property (nonatomic, copy)   NSString         *strCitycode;
///区
@property (nonatomic, copy)   NSString         *strDistrict;
///区域编码
@property (nonatomic, copy)   NSString         *strAdcode;
@end

#define KTopAddressHeight    130 //150

@implementation MapViewController
- (NSMutableArray *)searchPoiArray
{
     if (_searchPoiArray == nil)
     {
          _searchPoiArray = [[NSMutableArray alloc] init];
     }
     return _searchPoiArray;
}
- (NSMutableArray *)tipsArray {
     if (!_tipsArray) {
          _tipsArray = [[NSMutableArray alloc] init];    }
     return _tipsArray;
}


- (void)viewDidLoad {
     [super viewDidLoad];
     // Do any additional setup after loading the view.
     self.view.backgroundColor = [UIColor whiteColor];
     
     //Show classname while debug
     DLog(@"%@",NSStringFromClass([self class]));
     self.tempArray = [NSMutableArray new];
    
     [self initMapView];
     [self initSearch];
     [self initTableView];
     
     [self initCenterView];
     [self initAddressView];
     [self initBottomView];
     
     self.mapView.zoomLevel = 15;
     self.mapView.showsUserLocation = YES;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [self.view endEditing:YES];
    [self.searchText endEditing:YES];
    [self textFieldShouldEndEditing:self.searchText];
    [self removeMengBanView];
}

- (void)viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];

    WS(ws);
    [UIView animateWithDuration:0.2 animations:^{
        
        ws.bottomView.frame = CGRectMake(0, kScreenHeight-90-64, kScreenWidth, 90);
        ws.addressView.frame = CGRectMake(0, 0, kScreenWidth, KTopAddressHeight);
      
        if (ws.isChange) {
           CLLocationCoordinate2D location = CLLocationCoordinate2DMake(ws.mapInfoModel.latitude.floatValue, ws.mapInfoModel.longitude.floatValue);
           [ws.mapView setCenterCoordinate:location animated:YES];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                ws.AnnotationTitleLabel.text = ws.mapInfoModel.addressTitle ;
                ws.addressContentLabel.text = ws.mapInfoModel.address;
            });

        }else{
            [ws actionLocation];
        }

    } completion:nil];
    
    
    
//    if (ws.isChange) {
//       CLLocationCoordinate2D location = CLLocationCoordinate2DMake(ws.mapInfoModel.latitude.floatValue, ws.mapInfoModel.longitude.floatValue);
//       [ws.mapView setCenterCoordinate:location animated:YES];
//
//        ws.nameText.text = ws.mapInfoModel.name;
//        ws.phoneText.text = ws.mapInfoModel.phone;
//
////        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            ws.AnnotationTitleLabel.text = ws.mapInfoModel.addressTitle ;
//            ws.addressContentLabel.text = ws.mapInfoModel.addressContent;
////        });
//
//
//    }
    
}

- (void)initMapView
{
    
    self.strProvince = @"";
    self.strCity = @"";
    self.strCitycode = @"";
    self.strDistrict = @"";
    self.strAdcode = @"";

    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, kTopHeight, self.view.frame.size.width,self.view.frame.size.height)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
     
}

- (void)initTableView
{
     self.mengbanView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kScreenHeight-kTopHeight)];
     
     UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
     [keyWindow addSubview:self.mengbanView];
     self.mengbanView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
     //    self.mengbanView.alpha = 0.3;
     self.mengbanView.hidden = YES;
     self.mengbanView.userInteractionEnabled = YES;
     UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeMengBanView)];
     tapGesture.delegate = self;
     [self.mengbanView addGestureRecognizer:tapGesture];
     
     
     self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(8, 5,kScreenWidth-16, 200) style:UITableViewStylePlain];
     self.searchTableView.backgroundColor = [UIColor whiteColor];
     self.searchTableView.alpha = 1.0;
     self.searchTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
     self.searchTableView.delegate = self;
     self.searchTableView.dataSource = self;
     self.searchTableView.hidden = YES;
     [self.mengbanView addSubview:self.searchTableView];
     
}

- (void)initSearch
{
    self.searchPage = 1;
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;

    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(0, kStatusBarHeight,kScreenWidth,44)];
    [self.view addSubview:self.searchView];
    //    self.searchView.backgroundColor = [UIColor whiteColor];
    //    self.searchView.layer.borderWidth = 0.5;
    self.searchView.layer.borderColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0].CGColor;

    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 2, 40, 40)];
    [self.searchView addSubview:backButton];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];


    UIImageView * imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 10, 20)];
    imageview.image = [UIImage imageNamed:@"zcj_arrow_back"];
    [backButton addSubview:imageview];
    imageview.contentMode = UIViewContentModeScaleAspectFit;

    self.searchText = [[UITextField alloc] initWithFrame:CGRectMake(backButton.right + 3, 8, kScreenWidth-80, 30)];
    [self.searchView addSubview:self.searchText];
    self.searchText.placeholder = @"请填写查询条件";

    self.searchText.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.searchText.delegate = self;
    [self.searchText addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
    self.searchText.backgroundColor = [UIColor cjBackgroundColor];
    self.searchText.layer.cornerRadius = 17;
    self.searchText.clipsToBounds = YES;

    UIView *leftView = [[UIView alloc] init];
    leftView.frame = CGRectMake(0, 0, 50, 40);

    UIImageView *leftImg = [[UIImageView alloc] init];
    leftImg.frame = CGRectMake(20, 10, 20, 20);
    leftImg.image = [UIImage imageNamed:@"zcj_icon_search_gray"];
    leftImg.contentMode = UIViewContentModeScaleAspectFit;
    [leftView addSubview:leftImg];
    self.searchText.leftView = leftView;
    self.searchText.leftViewMode = UITextFieldViewModeAlways;

}


#pragma mark --- UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
     
     if ([touch.view isDescendantOfView:self.searchTableView]) {
          return NO;
     }
     return YES;
}

#pragma mark ----textFiledDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
     //开始编辑时触发，文本字段将成为first responder
     DLog(@"开始编辑");
     
     UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
     
     [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
          
          self.searchView.frame = CGRectMake(0, kStatusBarHeight,kScreenWidth,44);
          [keyWindow addSubview:self.mengbanView];
          self.mengbanView.hidden = NO;
          self.searchTableView.hidden = YES;
     } completion:nil];
     
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
     //返回BOOL值，指定是否允许文本字段结束编辑，当编辑结束，文本字段会让出first responder
     
     DLog(@"结束编辑");
    
     return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
     //当用户使用自动更正功能，把输入的文字修改为推荐的文字时，就会调用这个方法。
     
     //    [self searchTipsWithKey:textField.text];
     
     DLog(@"正在输入中");
     
     return YES;
}

-(void)textFieldTextChange:(UITextField *)textField{
    DLog(@"textField1 - 输入框内容改变,当前内容为: %@",textField.text);
     
     [self searchTipsWithKey:textField.text];
     
}

/* 输入提示 搜索.*/
- (void)searchTipsWithKey:(NSString *)key
{
     
     DLog(@"%@",self.cityName);
     
     if (key.length == 0)
     {
          return;
     }
     
     AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
     tips.keywords = key;
     tips.city     = self.cityName;
     tips.types = @"住宅|学校|楼宇|商场";
     tips.cityLimit = NO; //是否限制城市
     
     [self.search AMapInputTipsSearch:tips];
}

/* 输入提示回调. */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
     //解析response获取提示词，具体解析见 Demo
     if (response.count == 0)
     {
          return;
     }
     
     [self.tipsArray removeAllObjects];
     [self.tipsArray setArray:response.tips];
     self.searchTableView.hidden = NO;
     [self.searchTableView reloadData];
     
}

#pragma mark ----- tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
     
     return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     
     return self.tipsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     
     AMapTip *tip = self.tipsArray[indexPath.row];
     
     NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld",(long)indexPath.row];
     SearchCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     if (cell == nil) {
          cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
     }
     cell.selectionStyle = UITableViewCellSeparatorStyleSingleLine;
     cell.title = tip.name;
     cell.content = tip.address;
     
     return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     
     return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     
     AMapTip *tip = self.tipsArray[indexPath.row];
     [self.tempArray removeAllObjects];
     [self.tempArray addObject:tip];
     CLLocationCoordinate2D location = CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude);
     
     [self.mapView setCenterCoordinate:location animated:YES];
     
     self.searchTableView.hidden = YES;
     self.searchView.frame = CGRectMake(0, kStatusBarHeight,kScreenWidth,44);
     [self.mengbanView removeFromSuperview];
     self.searchText.text = tip.name ;
}

- (void)back {
     
     [self.navigationController popViewControllerAnimated:YES];
}
- (void)removeMengBanView {
     [self.mengbanView removeFromSuperview];
     [self.searchText resignFirstResponder];
     [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
          
          self.searchView.frame = CGRectMake(0, kStatusBarHeight,kScreenWidth,44);
          
     } completion:nil];
}

//视图中心的大头针
- (void)initCenterView
{
     self.centerAnnotationView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zcj_wateRedBlank"]];
     self.centerAnnotationView.center = CGPointMake(self.mapView.center.x, self.mapView.center.y - CGRectGetHeight(self.centerAnnotationView.bounds)/2-32);
     
     [self.mapView addSubview:self.centerAnnotationView];
     
     self.annotationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 60)];
     self.annotationView.center = CGPointMake(self.mapView.center.x, self.mapView.center.y-self.centerAnnotationView.frame.size.height-CGRectGetHeight(self.annotationView.bounds)/2-32);
     self.annotationView.backgroundColor = [UIColor whiteColor];
     self.annotationView.layer.borderWidth = 0.5;
     self.annotationView.layer.borderColor = [UIColor lightGrayColor].CGColor;
     [self.mapView addSubview:self.annotationView];
     
     self.AnnotationTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, 230, 20)];
     self.AnnotationTitleLabel.font = [UIFont cjTitleFont16];
     self.AnnotationTitleLabel.textColor = [UIColor blackColor];
     self.AnnotationTitleLabel.textAlignment = NSTextAlignmentLeft;
     self.AnnotationTitleLabel.text = @"搜索中";
     [self.annotationView addSubview:self.AnnotationTitleLabel];
     
     self.AnnotationContentLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, CGRectGetMaxY(self.AnnotationTitleLabel.frame), 230, 35)];
     self.AnnotationContentLabel.font = [UIFont cjTitleFont12];
     self.AnnotationContentLabel.textColor = [UIColor grayColor];
     self.AnnotationContentLabel.textAlignment = NSTextAlignmentLeft;
     self.AnnotationContentLabel.lineBreakMode = NSLineBreakByClipping;
     self.AnnotationContentLabel.numberOfLines = 0;
     self.AnnotationContentLabel.text = @"搜索中";
     [self.annotationView addSubview:self.AnnotationContentLabel];
}

- (void)initAddressView{
    
    CGRect rcFrame = CGRectMake(0, -KTopAddressHeight, kScreenWidth, 0);
    self.addressView = [[FlexFrameView alloc] initWithFlex:@"MapVCHeaderView" Frame:rcFrame Owner:self];
    self.addressView.flexibleHeight = YES;

    
    [self.addressView layoutIfNeeded];

    DLog(@"---%f",self.addressView.height);
    [self.mapView addSubview:self.addressView];

    
}

- (void)initBottomView
{
     
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,kScreenHeight, kScreenWidth, 90)];
    [self.mapView addSubview:self.bottomView];
    self.bottomView.backgroundColor = [UIColor clearColor];
    //    self.bottomView.alpha = 1.0;

    self.sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(20,20, kScreenWidth -40, 50)];
    self.sureBtn.backgroundColor =  [UIColor cjMainColor];//RGB(6, 196, 82);
    [self.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sureBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.bottomView addSubview:self.sureBtn];
    [self.sureBtn addTarget:self action:@selector(makeSure) forControlEvents:UIControlEventTouchUpInside];
    self.sureBtn.clipsToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
}

- (void)makeSure{
    
//    MapInfoModel *model = [[MapInfoModel alloc]init];
    self.mapInfoModel.addressTitle = self.addressTitleLabel.text;
    self.mapInfoModel.address = self.addressContent;

    self.mapInfoModel.latitude = CJStringWithFormat(@"%lf",self.locationCoordinate.latitude);
    self.mapInfoModel.longitude = CJStringWithFormat(@"%f",self.locationCoordinate.longitude);

    
    if ([self.mapInfoModel.latitude isEqualToString:@""] || [self.mapInfoModel.longitude isEqualToString:@""] || [self.mapInfoModel.addressTitle isEqualToString:@""]) {
        [CJAlert showStringDismissWithDelay:@"定位中，请稍等"];
        return;
    }
    
    self.mapInfoModel.province = self.strProvince;
    self.mapInfoModel.provinceCode = self.strProvinceCode;
    self.mapInfoModel.city = self.strCity;
    self.mapInfoModel.cityCode = self.strCitycode;
    self.mapInfoModel.district = self.strDistrict;
    self.mapInfoModel.adcode = self.strAdcode;
    
    if (self.blockMapInfo) {
        self.blockMapInfo(self.mapInfoModel);
        [self pop];
    }
    
    
}

- (void)pop {
    if (self.navigationController == nil) return ;
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Handle Action

- (void)actionSearchAroundAt:(CLLocationCoordinate2D)coordinate
{
//    逆地址编码查询接口
    [self searchReGeocodeWithCoordinate:coordinate];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self searchPoiWithCenterCoordinate:coordinate];
         self.searchPage = 1;
        [self centerAnnotationAnimimate];
        
    });
    

}

/* 移动窗口弹一下的动画 */
- (void)centerAnnotationAnimimate
{
     [UIView animateWithDuration:0.5
                           delay:0
                         options:UIViewAnimationOptionCurveEaseOut
                      animations:^{
                           CGPoint center = self.centerAnnotationView.center;
                           center.y -= 20;
                           [self.centerAnnotationView setCenter:center];}
                      completion:nil];
     
     [UIView animateWithDuration:0.45
                           delay:0
                         options:UIViewAnimationOptionCurveEaseIn
                      animations:^{
                           CGPoint center = self.centerAnnotationView.center;
                           center.y += 20;
                           [self.centerAnnotationView setCenter:center];}
                      completion:nil];
     
     /*    ---------------      */
     [UIView animateWithDuration:0.5
                           delay:0
                         options:UIViewAnimationOptionCurveEaseOut
                      animations:^{
                           CGPoint center = self.annotationView.center;
                           center.y -= 20;
                           [self.annotationView setCenter:center];}
                      completion:nil];
     
     [UIView animateWithDuration:0.45
                           delay:0
                         options:UIViewAnimationOptionCurveEaseIn
                      animations:^{
                           CGPoint center = self.annotationView.center;
                           center.y += 20;
                           [self.annotationView setCenter:center];}
                      completion:nil];
     
}

/* 根据中心点坐标来搜周边的POI. */
- (void)searchPoiWithCenterCoordinate:(CLLocationCoordinate2D )coord
{
     AMapPOIAroundSearchRequest*request = [[AMapPOIAroundSearchRequest alloc] init];
     
     request.location = [AMapGeoPoint locationWithLatitude:coord.latitude  longitude:coord.longitude];
     
     request.radius   = 2000;
     request.types = @"住宅|学校|楼宇|商场|道路";
     request.sortrule = 0;
     request.page     = self.searchPage;
     
     //将经纬度保存
     self.locationCoordinate = coord;
     
     [self.search AMapPOIAroundSearch:request];
}

/// 逆地址编码查询接口
/// @param coordinate <#coordinate description#>
- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
     AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
     
     regeo.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
     regeo.requireExtension = YES;
     regeo.poitype = @"住宅|学校|楼宇|商场|道路";
     
     //将经纬度保存
     self.locationCoordinate = coordinate;
     
     [self.search AMapReGoecodeSearch:regeo];
}


/// 回到当前定位
- (void)actionLocation
{
     if (self.mapView.userTrackingMode == MAUserTrackingModeFollow)
     {
          [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
     }
     else
     {
          self.searchPage = 1;
          
          [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
          
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
               // 因为下面这句的动画有bug，所以要延迟0.5s执行，动画由上一句产生
               [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
          });
     }
}

#pragma mark - MapViewDelegate
//地图区域改变完成后会调用此接口
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
     if (self.mapView.userTrackingMode == MAUserTrackingModeNone)
     {
          [self actionSearchAroundAt:self.mapView.centerCoordinate];
     }
    
}
//地图将要发生移动时调用此接口
- (void)mapView:(MAMapView *)mapView mapWillMoveByUser:(BOOL)wasUserAction
{
     [UIView animateWithDuration:0.3 animations:^{
          self.bottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 90);
          self.addressView.frame = CGRectMake(0,-KTopAddressHeight, kScreenWidth, KTopAddressHeight);
     } completion:nil];
     
}
//地图移动结束时调用此接口
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
     [UIView animateWithDuration:0.3 animations:^{
          self.bottomView.frame = CGRectMake(0, kScreenHeight-90-64, kScreenWidth, 90);
          self.addressView.frame = CGRectMake(0,0, kScreenWidth, KTopAddressHeight);
     } completion:nil];
     
}

#pragma mark - userLocation

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
     if(!updatingLocation)
          return ;
     
     if (userLocation.location.horizontalAccuracy < 0)
     {
          return ;
     }
     
     // only the first locate used.
     if (self.isLocatedFirst)
     {
          
//          self.isLocatedFirst = NO;
          self.mapView.userTrackingMode = MAUserTrackingModeFollow;
//          [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)];
          [self actionSearchAroundAt:userLocation.location.coordinate];
     }
}

- (void)mapView:(MAMapView *)mapView  didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
     if (mode == MAUserTrackingModeNone)
     {
//          [self.locationBtn setImage:self.imageNotLocate forState:UIControlStateNormal];
     }
     else
     {
//          [self.locationBtn setImage:self.imageLocated forState:UIControlStateNormal];
     }
}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
     DLog(@"error = %@",error);
     //
    [CJAlert showStringDismissWithDelay:@"定位失败，请移动位置重新定位"];
     
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
     if (response.regeocode != nil)
     {
          //解析response获取地址描述，具体解析见 Demo
          
          //        DLog(@"%@",response.regeocode.formattedAddress);
          self.cityName = response.regeocode.addressComponent.city;
          DLog(@"addressComponent is %@",response.regeocode.addressComponent.city);
         DLog(@"addressComponent is %@",response.regeocode.addressComponent.citycode);

         DLog(@"addressComponent is %@",response.regeocode.addressComponent.province);

         DLog(@"addressComponent is %@",response.regeocode.addressComponent.district);

         DLog(@"addressComponent is %@",response.regeocode.addressComponent.adcode);

         self.strProvince = response.regeocode.addressComponent.province;
         self.strProvinceCode = @"";
         self.strCitycode = response.regeocode.addressComponent.citycode;
         self.strCity = response.regeocode.addressComponent.city;
         self.strDistrict = response.regeocode.addressComponent.district;
         self.strAdcode = response.regeocode.addressComponent.adcode;
        
     }
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
     
     [self.searchPoiArray removeAllObjects];
     
     if (response != nil) {
          [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
              
              DLog(@"==== %@",obj.province);
              
              [self.searchPoiArray addObject:obj];
               //             DLog(@"+++++=%@",self.searchPoiArray)
          }];
     }
     if (self.searchPoiArray.count > 0) {
          [self refreshView];
     }
     
     
}

- (void)refreshView {
     
     if (self.tempArray.count >0) {
         
          AMapPOI *poi = self.tempArray[0];
        
         
         if (self.isChange) {
             self.isChange = NO;
         }else{
              self.addressTiele = poi.name;
              self.addressContent = poi.address;
//             DLog(@"==============  adcode = %@",poi.adcode);
//             DLog(@"==============  adcode = %@ %@ %@",poi.province ,poi.city ,poi.district );

              self.AnnotationTitleLabel.text = self.addressTiele ;
              self.AnnotationContentLabel.text = self.addressContent;
              self.addressTitleLabel.text = self.addressTiele;
              self.addressContentLabel.text = [NSString stringWithFormat:@"%@%@%@%@",self.strProvince,self.strCity,self.strDistrict,self.addressContent];
         }
         
          [self.tempArray removeAllObjects];
     }
     else
     {
          
          //          DLog(@"++++++++self.searchPoiArray == %@",self.searchPoiArray)
          
          AMapPOI *poi = self.searchPoiArray[0];
          
          //    DLog(@"%@",self.city);
          //    DLog(@"%@",poi);

         
         if (self.isChange) {
             self.isChange = NO;
         }else{
            self.addressTiele = poi.name;
            self.addressContent = poi.address;
            DLog(@"==============  adcode = %@ %@ %@",poi.province ,poi.city ,poi.district );

            self.AnnotationTitleLabel.text = self.addressTiele ;
            self.AnnotationContentLabel.text = self.addressContent;
            self.addressTitleLabel.text = self.addressTiele;
            //                  self.addressContentLabel.text = [NSString stringWithFormat:@"%@",self.addressContent];
            self.addressContentLabel.text = [NSString stringWithFormat:@"%@%@%@%@",self.strProvince,self.strCity,self.strDistrict,self.addressContent];
             if(self.isLocatedFirst){
                 self.isLocatedFirst = NO;
                 [self.mapView setCenterCoordinate:self.locationCoordinate];
             }
         }
         
          self.searchText.text = @"";
     }
}





- (void)didReceiveMemoryWarning {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end


